package cn.bigfire.wedesk.util;

import javax.imageio.ImageIO;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

public class ImgUtil {

    public static BufferedImage byte2img(byte[] bytes) {
        try {
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
            return ImageIO.read(bais);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] img2Byte(BufferedImage bufferedImage) {
        byte[] bytes = new byte[0];
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "jpg", baos);
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bytes;
    }

    public static BufferedImage zoomSize(BufferedImage img, int newWidth, int newHeight) {
        long start = System.currentTimeMillis();
        BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, img.getType());
        Graphics2D graphics = resizedImage.createGraphics();
        Image image = img.getScaledInstance(newWidth, newHeight, Image.SCALE_DEFAULT);
        graphics.drawImage(image, 0, 0, null);
        graphics.dispose();
        long end = System.currentTimeMillis();
        long cha = end - start;
        System.out.println("zoomByScale耗时:" + cha);
        return resizedImage;
    }
}
